/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODE_NET_TCP_SERVER_SOCKET_H_
#define NODE_NET_TCP_SERVER_SOCKET_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <event2/event.h>
#include <event2/listener.h>
#include "node/node.h"
#include "node/net/tcp_worker.h"

namespace node {
    namespace net {

        typedef void(*LISTEN_EVENT_CALLBACK)(::evutil_socket_t, struct sockaddr *, int, void *);

        class ServerSocket
        {
        public:
            ServerSocket(::node::net::TcpWorker &runnable, 
                LISTEN_EVENT_CALLBACK listen_callback = NULL, void *user_data = NULL);
            ~ServerSocket(void);

            bool open(const char *address, int port, int backlog);
            void close(void);

            inline void set_listen_callback(LISTEN_EVENT_CALLBACK callback) {
                listen_callback_ = callback;
            }
            inline void set_user_data(void *user_data) {
                user_data_ = user_data;
            }

        private:
            static void acceptCallback(
                struct evconnlistener *listener,
                evutil_socket_t fd,
                struct sockaddr *sa,
                int socklen,
                void *user_data
                );


            ::node::net::TcpWorker &runnable_;
            struct evconnlistener* acceptor_;
            void *user_data_;
            LISTEN_EVENT_CALLBACK listen_callback_;
            DISALLOW_COPY_AND_ASSIGN(ServerSocket);
        };

    }
}

#endif // NODE_NET_TCP_SERVER_SOCKET_H_
